package cn.com.yx.ms.service.impl;

import cn.com.yx.ms.application.web.ApiQueryBase;
import cn.com.yx.ms.domain.dbmodel.SysLog;
import cn.com.yx.ms.persistence.SysLogMapper;
import cn.com.yx.ms.service.ILogService;
import cn.com.yx.ms.service.IUserContextService;
import cn.yx.framework.configuration.BaseConstant;
import cn.yx.framework.context.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * ApphubServiceImpl
 */
@Service
@Transactional
public class UserContextServiceImpl implements IUserContextService {

    @Autowired
    HttpServletRequest httpServletRequest;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public UserContext getUserContext() {
        //return (UserContext)httpServletRequest.getSession().getAttribute(BaseConstant.CONTEXT_USER_PROFILE);
        UserContext userContext = null;
        if(redisTemplate.opsForValue().size(httpServletRequest.getSession().getId())>0){
            userContext =  (UserContext)redisTemplate.opsForValue().get(httpServletRequest.getSession().getId());
        }
        if(userContext == null){
            userContext = new UserContext();
            userContext.setId("-1");
        }
        return userContext;
    }

    @Override
    public void setUserContext(UserContext userContext) {
        httpServletRequest.getSession().setAttribute(BaseConstant.CONTEXT_USER_PROFILE, userContext);
        redisTemplate.opsForValue().set(httpServletRequest.getSession().getId(), userContext, BaseConstant.getRedisCacheConfig().getOvertime(), TimeUnit.SECONDS);
    }


}